package com.ds.servlet;

import com.ds.config.VerificationCode;
import com.ds.model.AjaxResult;
import com.ds.model.User;
import com.ds.service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    /**
     *这个请求用来返回验证码图片
     *
     * @throws ServletException
     * @throws IOException
     */

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求的会话
        HttpSession session = req.getSession();
        // 创建验证码对象
        VerificationCode verificationCode = new VerificationCode();
        // 获取验证码图片
        BufferedImage image = verificationCode.getImage();
        // 获取验证码文本
        String test = verificationCode.getTest();
        // 将验证码文本存到会话中
        session.setAttribute("code", test);
        // 向前端输出图片
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }


    /**
     * 登录请求应该是一个post请求
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       /*
       //获取请求体参数的输入字节流
        ServletInputStream inputStream = req.getInputStream();
        //转为字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        //读取请求体中的字符
        String s = bufferedReader.readLine();
        //通过jackson将json模板字符串反序列化为一个User对象
        User = new ObjectMapper().readValue(s, User.class);
        */
        ObjectMapper om = new ObjectMapper();
        User user = om.readValue(req.getInputStream(),User.class);
        AjaxResult result = userService.login(user,req);
        resp.setContentType("application/json;charset=utf-8");
        //将对象转为Json字符串
        String resultJson = om.writeValueAsString(result);
        resp.getWriter().write(resultJson);

    }
}

